<!--
 * @Author: 'Chenfarry' '2925102113@qq.com'
 * @Date: 2024-03-13 15:54:54
 * @LastEditors: 'Chenfarry' '2925102113@qq.com'
 * @LastEditTime: 2024-06-14 17:21:41
 * @FilePath: \liuyanggui\src\views\basicData\dishesType\components\editDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <cusDialog ref="dialogRef" :title="typeForm.id ? '修改' : '添加'" headCss="float:left;" @hideHandler="hideHandler"
      :confrimText="typeForm.id ? '修改' : '新增'" @confrim="confrimHandler">
      <el-form ref="typeFormRef" :model="typeForm" label-width="80px" :rules="rules">
        <el-form-item label="类型名称" prop="dishTypeName">
          <el-input v-model="typeForm.dishTypeName" maxlength="30" placeholder="请输入类型名称"></el-input>
        </el-form-item>
        <el-form-item label="类型编码" prop="code">
          <el-input v-model="typeForm.code" maxlength="30" placeholder="请输入类型编码"></el-input>
        </el-form-item>
      </el-form>
    </cusDialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { reqAddType, reqModifyType } from "@/api/business/dishes";
const router = useRouter();
const dialogRef = ref(null);
const typeFormRef = ref(null);

const formOrigin = () => ({
  dishTypeName: "",
  code: "",
  id: "",
});

const typeForm = ref(formOrigin());

const emits = defineEmits<{
  (event: "onInit"): void;
}>();

const rules = reactive({
  dishTypeName: { required: true, message: "类型名称必填", tirgger: "blur" },
  code: [
    { required: true, message: "类型编码必填", tirgger: "blur" },
    // { pattern: "^d{n}$", message: "编码为三位数字", tirgger: "blur" },
  ],
});

// 展示对话框
const showHandler = (row) => {
  if (row) {
    typeForm.value = row;
    console.log(row);
  }
  dialogRef.value.show = true;
};
// 对话框关闭重置初始数据
const hideHandler = () => {
  typeForm.value = formOrigin();
  typeFormRef.value.resetFields();
};

const getAddType = () => {
  let { dishTypeName, code } = typeForm.value;
  reqAddType({ dishTypeName, code }).then((res) => {
    if (res.code == 1) {
      ElMessage.success("添加成功");
      dialogRef.value.show = false;
      emits("onInit");
    } else {
      ElMessage.info(res.msg);
    }
  });
};

const getModifyType = () => {
  reqModifyType({ ...typeForm.value }).then((res) => {
    if (res.code == 1) {
      ElMessage.success("修改成功");
      dialogRef.value.show = false;
      emits("onInit");
    } else {
      ElMessage.info(res.msg);
    }
  });
};
const confrimHandler = () => {
  typeFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (typeForm.value.id) {
        getModifyType();
      } else {
        getAddType();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

defineExpose({ showHandler });
</script>

<style lang="scss" scoped></style>